﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuanLyGiaoVuService.CommandServices;
using QuanLyGiaoVuService.ReportServices;
using QuanLyGiaoVuDAL.DTO;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using QuanLyGiaoVuUI.Models;

namespace QuanLyGiaoVuUI.Controllers
{
    public class DangNhapClientController : Controller
    {
        //
        // GET: /DangNhap/
        private INguoiDungCommandService _nguoiDungCommandService;
        private INguoiDungReportService _nguoiDungReportService;
        private IGiangVienReportService _giangVienReportService;
        private ISinhVienReportService _sinhVienReportService;

        public DangNhapClientController(INguoiDungCommandService nguoiDungCommandService,INguoiDungReportService nguoiDungReportService, IGiangVienReportService giangVienReportService, ISinhVienReportService sinhVienReportService)
        {
            _nguoiDungCommandService = nguoiDungCommandService;
            _nguoiDungReportService = nguoiDungReportService;
            _giangVienReportService = giangVienReportService;
            _sinhVienReportService = sinhVienReportService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GiangVienDangNhap()
        {
            return View();
        }

        [HttpPost]
        public JsonResult DangXuat()
        {
            Session["UserInfo"] = null;
            String url = "/DangNhapClient/GiangVienDangNhap";
            return Json(new { success = url });
        }

        [HttpPost]
        public ActionResult GiangVienDangNhap(String taiKhoanDangNhap, String matKhau, bool isGiangVien)
        {
            bool isSuccess = true;
            NguoiDungDTO nguoiDungDTO = new NguoiDungDTO();
            nguoiDungDTO.TaiKhoanDangNhap = taiKhoanDangNhap;
            nguoiDungDTO.MatKhau = matKhau;
            nguoiDungDTO.MatKhauMoi = "";
            nguoiDungDTO.IsGiangVien = isGiangVien;
            NguoiDungDTO temp = _nguoiDungReportService.DangNhapNguoiDung(nguoiDungDTO);
            if (temp==null)
            {
                isSuccess = false;
                temp = new NguoiDungDTO();
                temp.TaiKhoanDangNhap = "Vui lòng kiểm tra thông tin đăng nhập!";
            }
            else
            {
                if (temp.VaiTro == 2)
                {
                    isSuccess = false;
                }
                else
                {
                    Session["UserInfo"] = temp;
                }
            }
            return Json(new { success = isSuccess,
                name=temp.TaiKhoanDangNhap,
                role = temp.VaiTro
            });
        }

        public ActionResult SinhVienDangNhap()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SinhVienDangNhap(String taiKhoanDangNhap, String matKhau, bool isGiangVien)
        {
            bool isSuccess = true;
            NguoiDungDTO nguoiDungDTO = new NguoiDungDTO();
            nguoiDungDTO.TaiKhoanDangNhap = taiKhoanDangNhap;
            nguoiDungDTO.MatKhau = matKhau;
            nguoiDungDTO.MatKhauMoi = "";
            nguoiDungDTO.IsGiangVien = isGiangVien;
            NguoiDungDTO temp = _nguoiDungReportService.DangNhapNguoiDung(nguoiDungDTO);
            if (temp == null)
            {
                isSuccess = false;
                temp = new NguoiDungDTO();
                temp.TaiKhoanDangNhap = "Vui lòng kiểm tra thông tin đăng nhập!";
            }
            else
            {
                if (temp.VaiTro == 1)
                {
                    return Redirect("/DangNhapClient/GiangVienDangNhap");
                }
                else
                {
                    Session["SinhVienInfo"] = temp;
                }
            }
            return Json(new { success = isSuccess, name = temp.TaiKhoanDangNhap });
        }

        [AllowAnonymous]
        [HandleError]
        public ActionResult ExternalLogin(bool? isSinhVien)
        {
            return new ExternalLoginResult(OAuthWebSecurity.RegisteredClientData.First().AuthenticationClient.ProviderName, Url.Action("ExternalLoginCallback", new { ReturnUrl = String.Empty, IsSinhVien = (isSinhVien.HasValue && isSinhVien.Value) }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl, bool isSinhVien)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl, IsSinhVien = isSinhVien }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }


            if (!isSinhVien)
            {
                var email = result.UserName;

                NguoiDungDTO nguoiDung = _nguoiDungReportService.GetNguoiDungByTaiKhoan(email);
                if (nguoiDung != null)
                {
                    if (nguoiDung.VaiTro == 0)
                    {
                        Session["UserInfo"] = nguoiDung;
                        return RedirectToAction("Index", "GiangVien", null);
                    }
                    else
                        if (nguoiDung.VaiTro == 1)
                        {
                            Session["UserInfo"] = nguoiDung;
                            return RedirectToAction("Index", "GiangVienClient", null);
                        }
                        else
                            return RedirectToLocal(String.Empty);
                }
                else
                    return RedirectToLocal(String.Empty);
            }
            else
            {
                var email = result.UserName;
                var strArray = email.Split('@');
                string mssv = string.Empty;
                string domain = string.Empty;
                if (strArray.Length == 2)
                {
                    mssv = strArray[0];
                    domain = strArray[1];
                }
                if (!domain.ToLower().Contains("gm.uit.edu.vn"))
                    return RedirectToLocal(string.Empty);
                var sinhVienDTO = _sinhVienReportService.GetSinhVienByMSSV(mssv);
                if (sinhVienDTO != null)
                {
                    NguoiDungDTO nguoiDung = new NguoiDungDTO();
                    nguoiDung.MaNguoiDung = sinhVienDTO.ID;
                    nguoiDung.IsGiangVien = false;
                    nguoiDung.VaiTro = 2;
                    nguoiDung.TaiKhoanDangNhap = mssv;
                    Session["SinhVienInfo"] = nguoiDung;
                    return RedirectToAction("Index", "SinhVien", null);
                }
                else
                    return RedirectToLocal(string.Empty);
            }

            //if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            //{
            //    return RedirectToLocal(returnUrl);
            //}

            //if (User.Identity.IsAuthenticated)
            //{
            //    // If the current user is logged in add the new account
            //    OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
            //    return RedirectToLocal(returnUrl);
            //}
            //else
            //{
            //    // User is new, ask for their desired membership name
            //    string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
            //    ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            //    ViewBag.ReturnUrl = returnUrl;
            //    return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            //}
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("GiangVienDangNhap", "DangNhapClient");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                try
                {
                    OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
                }
                catch (Exception exception)
                { 

                }
            }
        }
        #endregion
    }
}
